package com.ruoyi.tranShort.mqtt.request;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.mqtt.api.MqttClientApi;
import com.ruoyi.tranShort.mqtt.CheckUtil;
import com.ruoyi.tranShort.mqtt.ResponseHandle;
import com.ruoyi.tranShort.mqtt.api.GatewayRequest;
import com.ruoyi.tranShort.mqtt.api.GatewayResponse;
import com.ruoyi.tranShort.mqtt.common.constants.ControllerNumberConstants;
import com.ruoyi.tranShort.mqtt.common.constants.TypeConstants;
import com.ruoyi.tranShort.mqtt.entity.ComType;
import com.ruoyi.tranShort.mqtt.entity.Content;
import com.ruoyi.tranShort.mqtt.entity.RequestBase;
import com.ruoyi.tranShort.mqtt.exception.ResponseTimeOutException;
import com.ruoyi.tranShort.mqtt.request.entity.SendMessageData;
import com.ruoyi.tranShort.mqtt.response.ConnectDeviceLongResponse;
import com.ruoyi.tranShort.mqtt.response.SendMessageResponse;
import com.ruoyi.tranShort.utils.MqttClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 发送信息
 * @author wwy
 * @date 2021-08-10 21:10
 */
public class SendMessageRequest implements GatewayRequest {
    private static final Logger LOGGER = LoggerFactory.getLogger(SendMessageRequest.class);
    private RequestBase requestBase = new RequestBase();
    private ComType comType = new ComType();
    private Content content = new Content();

    public SendMessageRequest() {
        requestBase.setComType(comType);
        comType.setClientId("");
        comType.setMsgId(System.currentTimeMillis()+"");
        comType.setType(TypeConstants.DOWN);
        comType.setContent(content);
        content.setType(TypeConstants.PASSTHROUGH);
    }

    /**
     * 透传消息
     */
    private String message;
    private String mac;
    private String pubTopic;
    private int qos;

    @Override
    public SendMessageResponse execute() {
        //初始化响应参数
        SendMessageResponse sendMessageResponse = new SendMessageResponse();
        sendMessageResponse.setCode(500);
        if(StringUtils.isNotEmpty(message)){
            String dataHexStr = convertStringToUTF8(message);
            int strLength =  message.getBytes().length+1;
            String hexStr = Integer.toHexString(strLength);
            String message1 = "";
            if(hexStr.length()==1){
                message1 = ControllerNumberConstants.SEND_MESSAGE+"0" + hexStr + "00fe" + dataHexStr;
            }
            if(hexStr.length()==2){
                message1 = ControllerNumberConstants.SEND_MESSAGE+"" + Integer.toHexString(strLength) + "00fe" + dataHexStr;
            }
            //校验码
            String checkStr = CheckUtil.makeChecksum(message1);

            String lastMessage = message1+checkStr+"16";
            SendMessageData sendMessageData = new SendMessageData();
            sendMessageData.setMac(mac);
            sendMessageData.setData(lastMessage);
            content.setData(sendMessageData);
            //发送消息
            MqttClientApi mqttClientApi = MqttClientUtil.getMqttClientApi();
            String message = JSONObject.toJSONString(requestBase);
            LOGGER.info("发送消息内容：{}",message);
            mqttClientApi.publishMessage(pubTopic,message,qos);
            try {
                String waitMessage = ResponseHandle.waitMessage(mac);
                //解析响应信息
                String conStr = waitMessage.substring(0, 4);
                if(ControllerNumberConstants.REPLY_MESSAGE.equals(conStr)){
                    //成功
                    sendMessageResponse.setCode(200);
                }
            } catch (ResponseTimeOutException e) {
                sendMessageResponse.setCode(500);
            }
        }
        return sendMessageResponse;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getPubTopic() {
        return pubTopic;
    }

    public void setPubTopic(String pubTopic) {
        this.pubTopic = pubTopic;
    }

    public int getQos() {
        return qos;
    }

    public void setQos(int qos) {
        this.qos = qos;
    }

    public String getMac() {
        return mac;
    }

    public void setMac(String mac) {
        this.mac = mac;
    }

    public String convertStringToUTF8(String s) {
        if (s == null || s.equals("")) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        try {
            char c;
            for (int i = 0; i < s.length(); i++) {
                c = s.charAt(i);
                if (c >= 0 && c <= 255) {
                    String s1 = Integer.toHexString(c);
                    sb.append(s1);
                } else {
                    byte[] b;

                    b = Character.toString(c).getBytes("utf-8");
                    for (int j = 0; j < b.length; j++) {
                        int k = b[j];
                        if (k < 0){
                            k += 256;
                        }

                        sb.append(Integer.toHexString(k));
                        // sb.append("%" +Integer.toHexString(k).toUpperCase());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return sb.toString();
    }


}
